<template>
  <div>
    <el-upload
      ref="upload"
      class="drive-uploader"
      :action="actionUrl"
      :show-file-list="false"
      :on-success="handleSuccess"
      :before-upload="handleBeforeUpload"
      :headers="{
        'agent': 'Web',
        'token': token,
      }"
    >
      <img
        v-if="row.driveimg && row.id"
        :src="row.host+row.driveimg"
        class="drive"
      >
      <img
        v-if="url && row.driveimg && !row.id"
        :src="host+url"
        class="drive"
      >
      <i
        v-if="!row.driveimg"
        class="el-icon-plus drive-uploader-icon"
      />
    </el-upload>
  </div>
</template>
<script>
import { getToken } from '@/utils/auth'
export default {
  name: 'UploadDriveImg',
  props: {
    folder: {
      type: String,
      default: ''
    },
    row: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      url: '',
      host: '',
      actionUrl: '',
      loadingStatus: false,
      uploadList: [],
      imgName: '',
      token: getToken()
    }
  },
  mounted() {
    this.uploadList = this.$refs.upload.fileList
    this.actionUrl = process.env.NODE_ENV === 'development' ? `http://localhost:9528/dev-api/upload?folder=${this.folder}` : `http://47.97.156.168/upload?folder=${this.folder}`
  },
  methods: {
    handleSuccess(response, file, fileList) {
      this.uploadList = fileList
      file.url = response.host + response.data
      this.host = response.host
      this.url = response.data
      this.$emit('upload-success', this.url)
    },
    handleBeforeUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size < 500 * 1024
      this.fileName = file.name
      if (!isJPG && !isPNG) {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 500KB!')
      }
      return (isJPG || isPNG) && isLt2M
    }
  }
}
</script>
<style>
  .drive-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .drive-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .drive-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 200px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }
  .drive {
    width: 200px;
    height: 120px;
    display: block;
  }
</style>
